package chu.dejian.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
import java.util.List;
import com.sam.blemodule.R;
import com.sam.utils.display.ScreenUtils;
import com.sam.widget.badge.BadgeView;

public class ViewPagerNavBar extends LinearLayout {
	private Context context;
	private LayoutInflater inflater;
	private int viewPagerResId;
	private String firstTabName;
	private String secondTabName;
	private String thirdTabName;
	private RadioGroup radioGroup;
	private ViewPager mPager;
	private ImageView cursor;
	private RadioButton firstTab, secondTab, thirdTab;
	private int offset = 0;
	private int currIndex = 0;
	private int bmpW,secondX,thirdX,tabWidth;

	BadgeView badge1,badge2,badge3;

	public ViewPagerNavBar(Context context) {
		this(context, null);
	}

	public ViewPagerNavBar(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ViewPagerNavBar(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.context = context;
		getAttrs(context,attrs);
		findView();
		initView();
	}

	protected void getAttrs(Context context, AttributeSet attrs){
		TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.ViewPagerNavBar);
//		viewPagerResId = ta.getInt(R.styleable.ViewPagerNavBar_bindViewPager, 0);
		firstTabName = ta.getString(R.styleable.ViewPagerNavBar_firstTabName);
		secondTabName = ta.getString(R.styleable.ViewPagerNavBar_secondTabName);
		thirdTabName = ta.getString(R.styleable.ViewPagerNavBar_thirdTabName);
		ta.recycle();
	}

	private void findView(){
		inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.widget_viewpager_navbar, this);
//		mPager = (ViewPager) findViewById(viewPagerResId);
		radioGroup = (RadioGroup) findViewById(R.id.tab_nav_bar);
		firstTab = (RadioButton) findViewById(R.id.first_tab);
		secondTab = (RadioButton) findViewById(R.id.second_tab);
		thirdTab = (RadioButton) findViewById(R.id.third_tab);
	}

	public void initView() {
		firstTab.setText(firstTabName);
		secondTab.setText(secondTabName);
		thirdTab.setText(thirdTabName);
		firstTab.setOnClickListener(onClickListener);
		secondTab.setOnClickListener(onClickListener);
		thirdTab.setOnClickListener(onClickListener);
		badge1 = new BadgeView(context, firstTab);
		badge2 = new BadgeView(context, secondTab);
		badge3 = new BadgeView(context, thirdTab);
		InitImageView();
		setCursorLine(0);
	}



	public void setTabTagText(int tabIndex,String tagText){
		switch (tabIndex){
			case 0:
				badge1.setText(tagText);
				badge1.show();
				break;
			case 1:
				badge2.setText(tagText);
				badge2.show();
				break;
			case 2:
				badge3.setText(tagText);
				badge3.show();
				break;
			default:
				Log.e("chuchuyajun","setTabTagText的第一个参数为0-2");
				break;
		}
	}

	public void hideTabTag(int tabIndex){
		switch (tabIndex){
			case 0:
				badge1.hide();
				break;
			case 1:
				badge2.hide();
				break;
			case 2:
				badge3.hide();
				break;
		}
	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
//			if(mPager == null) throw new NullPointerException("必须绑定ViewPager,调用bindViewPager函数即可");
			int i = v.getId();
			if (i == R.id.first_tab) {
				setCurrentTab(0);

			} else if (i == R.id.second_tab) {
				setCurrentTab(1);

			} else if (i == R.id.third_tab) {
				setCurrentTab(2);

			} else {
			}
		}
	};

	public void setCurrentTab(int index){
		if(index < 0 || index > 2) return;
//		setCursorLine(index);
		firstTab.setChecked(index == 0);
		secondTab.setChecked(index == 1);
		thirdTab.setChecked(index == 2);
		if(mPager != null) mPager.setCurrentItem(index);
	}

	private void InitImageView() {
		cursor = (ImageView) findViewById(R.id.cursor);
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.indicate_line).getWidth();
		tabWidth = ScreenUtils.getScreenWidth(context) / 3;
		offset = (tabWidth - bmpW) / 2;
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);
		secondX = offset * 2 + bmpW;
		thirdX = secondX * 2;
	}

	/**
	 * 每次光标移动，在执行完动画后直接把光标的位置设置到动画移动后的位置。这样即使切换回画面
	 * 光标的位置还是最后一次的位置。不过这种做法也有弊端。就是如果机器配置稍微低点，会看到动画
	 * 执行完后光标会先回到最开始的位置，然后再移动到相应的地方。这种方式使得此控件和页面的耦合度更低
	 * @param position
     */
	private void setCursorLine2(int position){
		if(currIndex == position) return;
		Animation animation = new TranslateAnimation(0, (position - currIndex) * tabWidth, 0, 0);
		animation.setAnimationListener(new CursorAnimationListener(position));
		currIndex = position;
		animation.setFillAfter(false);
		animation.setDuration(300);
		cursor.startAnimation(animation);
	}

	/**
	 * 因为动画在切换到其他页面返回后动画会还原、也就是这个光标在回到本页面后又回到了第一个条目上。
	 * 为了解决这个问题，需要在页面的onResume事件中调用这个resetCursorLine函数来恢复到原来的位置上。
	 * 不过还有一种解决办法、就是调用setCursorLine2进行光标设置。这种方法是每次光标移动，在执行完动画
	 * 后直接把光标的位置设置到动画移动后的位置。这样即使切换回画面光标的位置还是最后一次的位置。不过
	 * 这种做法也有弊端。就是如果机器配置稍微低点，会看到动画执行完后光标会先回到最开始的位置，然后
	 * 再移动到相应的地方。
	 */
	public void resetCursorLine(){
		Animation animation = null;
		if(currIndex == 0) return;
		else if(currIndex == 1) animation = new TranslateAnimation(0, secondX, 0, 0);
		else if(currIndex == 2) animation = new TranslateAnimation(0, thirdX, 0, 0);
		animation.setFillAfter(true);
		animation.setDuration(300);
		cursor.startAnimation(animation);
	}

	private void setCursorLine(int position){
		if(currIndex == position) return;
		Animation animation = null;
		switch (position) {
			case 0:
				if (currIndex == 1) {
					animation = new TranslateAnimation(secondX, 0, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(thirdX, 0, 0, 0);
				}
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, secondX, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(thirdX, secondX, 0, 0);
				}
				break;
			case 2:
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, thirdX, 0, 0);
				} else if (currIndex == 1) {
					animation = new TranslateAnimation(secondX, thirdX, 0, 0);
				}
				break;
		}
		currIndex = position;
		animation.setFillAfter(true);
		animation.setDuration(300);
		cursor.startAnimation(animation);
	}

	public void setPages(ViewPager viewPager,List<View> pageList){
		this.mPager = viewPager;
//		this.mPager.requestDisallowInterceptTouchEvent(true); // 优先让子View处理滑动事件
		if(pageList.size() < 3) throw new IndexOutOfBoundsException("要设置的页面数量必须为3");
		else initViewPager(pageList);
	}

	public void setPages(ViewPager viewPager,int[] pageResIds){
		this.mPager = viewPager;
		if(pageResIds.length < 3) throw new IndexOutOfBoundsException("要设置的页面数量必须为3");
		else {
			List<View> pages = new ArrayList<View>();
			pages.add(inflater.inflate(pageResIds[0],null));
			pages.add(inflater.inflate(pageResIds[1],null));
			pages.add(inflater.inflate(pageResIds[2],null));
			initViewPager(pages);
		}
	}

	private void initViewPager(List<View> pages) {
		if(mPager == null) throw new NullPointerException("必须绑定ViewPager,调用setPages函数即可");
		mPager.setAdapter(new MyPagerAdapter(pages));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(onPageChangeListener);
	}

	public ViewPager getBindedViewPager(){
		return mPager;
	}

	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}


	class CursorAnimationListener implements Animation.AnimationListener{
		private int index = 0;
		public CursorAnimationListener(int cursorIndex){
			index = cursorIndex;
		}

		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			Matrix matrix = new Matrix();
			matrix.postTranslate(tabWidth * index + offset, 0);
			cursor.setImageMatrix(matrix);
		}

		@Override
		public void onAnimationRepeat(Animation animation) {

		}
	}

	private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
		@Override
		public void onPageScrolled(final int position, float positionOffset, int positionOffsetPixels) {

		}

		@Override
		public void onPageSelected(int position) {
			if(onPageChangeCallback != null) onPageChangeCallback.onPageChanged(position);
			setCursorLine(position);
		}

		@Override
		public void onPageScrollStateChanged(int state) {

		}
	};

	OnPageChangeCallback onPageChangeCallback;
	public void setOnPageChangeCallback(OnPageChangeCallback onPageChangeCallback){
		this.onPageChangeCallback = onPageChangeCallback;
	}

	public interface OnPageChangeCallback{
		void onPageChanged(final int position);
	}
}
